package com.dartfar.workflow.handler;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jbpm.api.jpdl.DecisionHandler;
import org.jbpm.api.model.OpenExecution;

import bsh.EvalError;
import bsh.Interpreter;

import com.dartfar.base.dao.DaoUtil;
import com.dartfar.base.model.BaseEntity;
import com.dartfar.util.SpringContextUtil;
import com.dartfar.util.StringUtils;
import com.dartfar.workflow.constant.WorkflowTradeType;
import com.dartfar.workflow.service.WorkflowPermissionServiceImpl;

/**
 * 工作流节点触发器
 * @author 王琦
 *
 */
public class WorkflowDecisionHandler implements DecisionHandler  {

	static Logger logger = Logger.getLogger(WorkflowDecisionHandler.class);
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<String> scriptNames = new ArrayList<String>();
	
	@Override
	public String decide(OpenExecution execution) {
		// TODO Auto-generated method stub
		try {
			//拿到DAO
			DaoUtil daoUtil = SpringContextUtil.getBean("daoUtil");
			String modelName = (String)execution.getVariable("BO_TYPE");
			String modelId = String.valueOf(execution.getVariable("BO_ID_VALUE"));
			logger.info("daoUtil: " + daoUtil);
			logger.info("modelName: " + modelName);
			logger.info("modelId : " + modelId);
			
			if(StringUtils.isNotEmpty(modelName) && StringUtils.isNotEmpty(modelId)) {
				Class clazz = Class.forName(modelName);
				BaseEntity entity = (BaseEntity) daoUtil.get(Integer.valueOf(modelId).intValue(), clazz);
				logger.info("entity: " + entity);
				logger.info("scriptNames: " + scriptNames);
				
				if(null != entity) {
					
					if(null != scriptNames && 0 != scriptNames.size()) {
						Boolean eval = false;
						Interpreter i = getInterpreterContext(entity);
						for(String el : scriptNames) {
							String[] elArray = el.split("->");
							if(2 == elArray.length) {
								String value = elArray[0];
								if(value.indexOf("&lt;")>=0){
									value = value.replace("&lt;", "<");
								}
								eval = (Boolean) i.eval(elArray[0]);
								if(eval) {
									return elArray[1];
								}
							} else {
								System.out.println("错误的表达式!");
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return WorkflowTradeType.SUBMIT;
	}

	/**
	 * 为Decision构建上下文环境
	 * @param i
	 * @param owner
	 * @param value
	 * @param modelId
	 * @param modelName
	 * @throws EvalError
	 */
	private Interpreter getInterpreterContext(Object owner) throws EvalError {
		Interpreter i = new Interpreter();
		i.set("_OWNER_OBJ", owner);
		return i;
	}
}
